package com.ks.mta.apiService;

import com.alibaba.fastjson.JSON;
import com.commonBean.Student;
import com.ks.api.service.StudentService;
import com.ks.mta.mapper.StudentMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Random;

/**
 * @program: SpringBootDemos
 * @description:
 * @author: Kangsen
 * @create: 2022-08-12 10:20
 **/
@DubboService(version = "1.0.0")
@Component
@Slf4j
public class ApiStudentService implements StudentService {

    @Resource
    private com.ks.mta.service.StudentService studentService;

    @Resource
    private StudentMapper studentMapper;

    /**
     * 获取所有的Student
     * @return
     */
    @Override
    public String getAllUser() {
        log.info("API GET ALL STUDENT");
        return JSON.toJSONString(studentService.studentAll());
    }

    /**
     * 添加学生
     * @param name
     * @param cla
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Student addStudent(String name, String cla) {
        Random random = new Random();
        int age = random.nextInt(100);
        Student student = Student.builder()
                .name(name)
                .cla(cla)
                .age(age).build();
        log.info("student:{}",student);
        int result = studentMapper.insert(student);
        log.info("result:{}",result);
        if(age <= 20){
            throw new RuntimeException("insert 异常  回滚一下！！！");
        }
        return student;
    }
}
